package com.example.wblog.interceptor;

import com.example.wblog.dao.LoginTicketDAO;
import com.example.wblog.dao.UserDAO;
import com.example.wblog.model.LoginTicket;
import com.example.wblog.model.User;
import com.example.wblog.util.CookieUtil;
import com.example.wblog.util.HostHolderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Component
public class PassportInterceptor implements HandlerInterceptor {

    @Autowired
    HostHolderUtil hostHolderUtil;

    @Autowired
    LoginTicketDAO loginTicketDAO;

    @Autowired
    UserDAO userDAO;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ticket = CookieUtil.getCookie("ticket", request);
        LoginTicket loginTicket = loginTicketDAO.selectByTicket(ticket);
        //invalid
        if (loginTicket == null || loginTicket.getExpired().before(new Date()) || loginTicket.getStatus() != 0) {
            return true;
        }
        hostHolderUtil.set(userDAO.selectById(loginTicket.getUserId()));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = hostHolderUtil.get();
        if (user == null) {
            return;
        }
        modelAndView.addObject("user", user);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        hostHolderUtil.clear();
    }
}
